import json
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import UserRolePermission, Role, User, Storehouse

# 权限管理视图
# Create your views here.


@xframe_options_exempt
def index(request):
    return render(request, "permission/index.html")


def permission_list(request):
    result = {"status": 1, "msg": "查询失败！"}
    data = request.GET
    try:
        page = data.get("page", 1)
        limit = data.get("limit", 5)
        search = data.get("search")

        pers = UserRolePermission.objects.filter(is_delete=0)
        if search and search != "":
            pers = pers.filter(Q(user__name__contains=search) | Q(role__name__contains=search) | Q(storehouse__name__contains=search))
        per_count = pers.count()
        paginator = Paginator(pers.order_by("-create_time"), limit)  # 每页多少条数据
        try:
            pers = paginator.page(page)  # 返回 page（页数）的数据
        except PageNotAnInteger:
            pers = paginator.page(1)  # 第一页
        except EmptyPage:
            pers = paginator.page(paginator.num_pages)  # 最后一页

        data_list = []
        for i in range(len(pers)):
            # 仓库名称
            pers_name = ""
            for per in pers[i].storehouse.order_by("-create_time").all():
                if len(pers_name) == 0:
                    pers_name += per.name
                else:
                    pers_name += f"|{per.name}"
            data_list.append({
                "No": i + 1,
                "id": pers[i].id,
                "user": pers[i].user.name,
                "role": pers[i].role.name,
                "storehouses": pers_name,
                "id_card": pers[i].user.id_card,
                "create_time": str(pers[i].create_time).split(".")[0],
            })

        result["data"] = data_list
        result["data_count"] = per_count
        result["status"] = 0  # layui parseData status=0 才认为是成功
        result["msg"] = "权限列表查询成功！"
    except Exception as e:
        print(e)
    return JsonResponse(result)


@xframe_options_exempt
def permission_add(request):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            user_id = data.get("user_id")
            role_id = data.get("role_id")
            # store_id = data.get("store_id")
            stores = data.get("stores")
            if not isinstance(stores, list):
                result["msg"] = "仓库递交方式错误！"
                return JsonResponse(result)
            route_exist = UserRolePermission.objects.filter(user_id=user_id, role_id=role_id, is_delete=0).first()
            if route_exist:
                result["msg"] = "请在已存在的员工角色中添加仓库范围！"
                return JsonResponse(result)
            role = Role.objects.filter(id=int(role_id), is_delete=0, status=1).first()
            if not role:
                result["msg"] = "选择的角色无效！"
                return JsonResponse(result)
            stores_exist = Storehouse.objects.filter(id__in=[int(i) for i in stores], status=1, is_delete=0).count()
            if len(stores) != stores_exist:
                result["msg"] = "存在无效仓库！"
                return JsonResponse(result)
            new_per = UserRolePermission.objects.create(user_id=user_id, role_id=role_id)
            new_per.storehouse.add(*[int(i) for i in stores])
            new_per.save()
            result["status"] = 1
            result["msg"] = "权限添加成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        users = User.objects.filter(is_delete=0).all()
        roles = Role.objects.filter(is_delete=0, status=1).all()
        stores = Storehouse.objects.filter(is_delete=0, status=1).all()
        return render(request, "permission/add.html", {"users": users, "roles": roles, "stores": stores})


@xframe_options_exempt
def permission_edit(request, per_id=None):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            user_id = data.get("user_id")
            role_id = data.get("role_id")
            stores = data.get("stores")
            per = UserRolePermission.objects.filter(id=int(per_id), is_delete=0).first()
            if not per:
                result["msg"] = "请确认该权限是否存在！"
                return JsonResponse(result)
            route_exist = UserRolePermission.objects.filter(user_id=user_id, role_id=role_id, is_delete=0).first()
            if route_exist and (route_exist.id != per.id):
                result["msg"] = "请在已存在的员工角色中修改仓库范围！"
                return JsonResponse(result)
            role = Role.objects.filter(id=int(role_id), is_delete=0, status=1).first()
            if not role:
                result["msg"] = "选择的角色无效！"
                return JsonResponse(result)
            # 判断仓库是否可用
            store_exist = Storehouse.objects.filter(id__in=[int(i) for i in stores], status=1, is_delete=0).count()
            if len(stores) != store_exist:
                result["msg"] = "存在不可用仓库！"
                return JsonResponse(result)
            per.user_id = user_id
            per.role_id = role_id
            # 更新权限与仓库的关系
            per.storehouse.clear()
            per.storehouse.add(*[int(i) for i in stores])
            per.save()
            result["status"] = 1
            result["msg"] = "权限信息更改成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        per = UserRolePermission.objects.filter(id=int(per_id), is_delete=0).first()
        roles = Role.objects.filter(is_delete=0, status=1).all()
        stores = Storehouse.objects.filter(is_delete=0, status=1).order_by("-create_time").all()
        return render(request, "permission/edit.html", {"per": per, "roles": roles, "stores": stores, "pitch_on_per": [i.id for i in per.storehouse.all()]})


def permission_del(request, per_id=None):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "DELETE":
        try:
            per = UserRolePermission.objects.filter(id=int(per_id), is_delete=0).first()
            if per:
                per.is_delete = 1
                per.save()
                result["status"] = 1
                result["msg"] = "权限删除成功！"
            else:
                result["msg"] = "请确认该权限是否存在"
        except Exception as e:
            print(e)
    return JsonResponse(result)


def permission_status(request, per_id=None):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            # print(data)
            status = data.get("status", None)
            if status is None or not isinstance(status, bool):
                result["msg"] = "请确认操作类型!"
                return JsonResponse(result)

            per = UserRolePermission.objects.filter(id=int(per_id), is_delete=0).first()
            if per:
                if status is True and per.status == 0:
                    per.status = 1
                if status is False and per.status == 1:
                    per.status = 0
                per.save()
                result["status"] = 1
                result["msg"] = "权限启用成功!" if status is True else "权限禁用成功！"
            else:
                result["msg"] = "请确认权限是否正确!"
        except Exception as e:
            print(e)
    return JsonResponse(result)

